package space.edge.d.demo.qrcode;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import space.edge.d.demo.qrcode.common.CharacterSetECI;
import space.edge.d.demo.qrcode.common.EncodeHintType;
import space.edge.d.demo.qrcode.common.ErrorCorrectionLevel;
import space.edge.d.demo.qrcode.exception.WriterException;
import space.edge.d.demo.qrcode.privatecode.CodeWriter;
import space.edge.d.demo.qrcode.privatecode.ui.CodeRenderer;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by gsl on 2017/11/10.
 */

public class CodeGeneratorActivity extends Activity {

    private EditText editText;
    private Button btn;
    private ImageView iv;

    private CodeWriter codeWriter;
    private CodeRenderer codeRenderer;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_code_generator);

        editText = (EditText) findViewById(R.id.edtv_input);
        btn = (Button) findViewById(R.id.btn_gen);
        iv = (ImageView) findViewById(R.id.iv_code);

        codeRenderer = new CodeRenderer();
        codeWriter = new CodeWriter();

        btn.setOnClickListener(clickListener);
        SQLiteDatabase db;

    }

    private void generateCode() {
        String text = editText.getText().toString();
        if (TextUtils.isEmpty(text))
            return;
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CharacterSetECI.UTF8);
        try {
            Bitmap bitmap = codeRenderer.render(codeWriter.encode(text, hints));
            if (bitmap != null)
                iv.setImageBitmap(bitmap);
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }

    private View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_gen:
                    generateCode();
                    break;
            }
        }
    };

    public static Intent newIntent(Context context) {
        return new Intent(context, CodeGeneratorActivity.class);
    }
}
